﻿/**************************************************************
 *
 * 唯一标识：e3805e72-dd91-4aef-a566-c25c24464b55
 * 命名空间：DotNetCore.CAP
 * 创建时间：2024/7/22 15:32:49
 * 机器名称：DESKTOP-HJ4OAG9
 * 创建者：CocoYuan
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：
 *
 **************************************************************/

using DotNetCore.CAP.Messages;
using Sgr;
using Sgr.Cap;
using Sgr.Utilities;
using System;
using System.Collections.Generic;

namespace DotNetCore.CAP
{
    public static class CapHeaderExtensions
    {
        //private static string Key_MessageMarkAsProcessed = "SGR-MarkAsProcessed";
        //private static string Key_MessageExceptionRetry = "SGR-ExceptionRetry";

        /// <summary>
        /// 获取消息的唯一标识
        /// </summary>
        /// <param name="header"></param>
        /// <returns></returns>
        public static string GetMessageId(this CapHeader header)
        {
            return header[Messages.Headers.MessageId]!;
        }

        /// <summary>
        /// 获取消息的发送时间
        /// </summary>
        /// <param name="header"></param>
        /// <returns></returns>
        public static DateTime? GetMessageSentTime(this CapHeader header)
        {
            if (DateTimeHelper.TryParseToUtc(header[Headers.SentTime], out DateTime sentTime))
                return sentTime;

            return null;
        }

        /// <summary>
        /// 当前消息是否因异常而重试
        /// </summary>
        /// <param name="header"></param>
        public static bool IsMessageExceptionRetry(this CapHeader header)
        {
            Check.NotNull(header, nameof(header));

            if (header.TryGetValue(Messages.Headers.Exception, out string? msg) && !string.IsNullOrEmpty(msg))
            {
                return msg!.Contains(nameof(CapMessageExceptionRetryException));
            }

            return false;
        }
    }
}